<template>
  <div class="categories">
    <h3>分类</h3>
    <ul>
      <li v-for="category in displayCategories" :key="category._id">
        <router-link :to="`/category/${category.id}`" class="category-link">
          {{ category.name }}({{ category.count }})
        </router-link>
      </li>
    </ul>
  </div>
</template>

<script setup>
import { defineProps, onMounted, watch, computed } from "vue";
import { FolderOutlined } from '@ant-design/icons-vue';
import { useBlogStore } from "../stores/blog";

// 定义组件的属性
const props = defineProps({
  categories: {
    type: Array,
    required: true,
    default: () => [],
  },
  useApi: {
    type: Boolean,
    required: false,
    default: false,
  },
});

// 使用 Pinia store
const blogStore = useBlogStore()

// 监听showInNav属性变化
watch(() => props.showInNav, () => {
  if (props.useApi) {
    fetchCategories()
  }
}, { immediate: false })

// 组件挂载时获取数据
onMounted(() => {
  if (props.useApi) {
    fetchCategories()
  }
})

// 计算最终显示的分类列表
const displayCategories = computed(() => {
  return props.useApi ? blogStore.cachedCategories : props.categories
})

// 获取分类列表
const fetchCategories = async () => {
  try {
    await blogStore.getCategories()
  } catch (error) {
    console.error('获取分类列表失败:', error)
  }
}
</script>

<style scoped>
.categories {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  border: 1px solid rgba(0, 0, 0, 0.05);
  margin-bottom: 24px;
}

.categories h3 {
  margin: 0 0 16px 0;
  font-size: 1.1rem;
  font-weight: 600;
  color: #333;
  position: relative;
  padding-bottom: 8px;
}

.categories h3::after {
  content: "";
  position: absolute;
  left: 0;
  bottom: 0;
  width: 40px;
  height: 2px;
  background: linear-gradient(to right, #1890ff, #722ed1);
}

.categories ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.categories li {
  margin-bottom: 12px;
}

.categories li:last-child {
  margin-bottom: 0;
}

.categories a {
  text-decoration: none;
  color: #666;
  font-size: 0.95rem;
  transition: all 0.3s ease;
  display: block;
  padding: 6px 0;
  border-radius: 4px;
}

.categories a:hover {
  color: #1890ff;
  background-color: #f0f7ff;
  padding-left: 8px;
}

.categories a::before {
  content: "";
  display: inline-block;
  width: 4px;
  height: 4px;
  border-radius: 50%;
  background-color: #ddd;
  margin-right: 8px;
  vertical-align: middle;
  transition: background-color 0.3s ease;
}

.categories a:hover::before {
  background-color: #1890ff;
}
</style>